<template>
  <view class="w-full max-w-[750rpx] mx-auto min-h-screen bg-[#f6f8fa] p-[32rpx] box-border">
    <backView />
    <text class="block text-[48rpx] font-extrabold mb-[40rpx] text-center text-blue-600 drop-shadow">编辑{{PageItem.title}}</text>
    <FormView v-if="form" :fieldConfig="fieldConfig" :form="form" :showButtons="true" @submit="submitForm" />
  </view>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import Taro from '@tarojs/taro'
import { pastMedicalFields as fieldConfig } from './fields'
import FormView from '@/components/FormView.vue'
import { request } from '@/service/request'
import { localStg } from '@/utils'
// import { getDemographicInfo } from '../../index/tooler'
import { PageItem } from './fields'
import backView from '@/components/backView.vue'

const form = ref<any>()

onMounted(async () => {
 const params = Taro.getCurrentInstance().router?.params
  if (params?.id) {
    // recordId.value = params.id
    await loadRecordData(params.id)
  }
})

async function loadRecordData(id: string) {
  try {
    const result = await request.get<any>(`${PageItem.commUrl}/queryById?id=${id}`, {}, {
      useErrMsg: true
    })

    console.log("result", result)
    
    if (result.success) {
      // Object.assign(form, result.success)
      form.value = result.success
    }
    console.log("form", form)
  } catch (error) {
    console.error('加载记录失败:', error)
    Taro.showToast({ title: '加载记录失败', icon: 'error' })
  }
}

async function submitForm(form: any, fieldConfig: any) {
  try {
    // 表单验证
    // if (!form.name) {
    //   Taro.showToast({ title: '请输入姓名', icon: 'error' })
    //   return
    // }
    // if (!form.sex) {
    //   Taro.showToast({ title: '请选择性别', icon: 'error' })
    //   return
    // }

    // 提交数据
    const params = {
      ...form,
      // id: recordId.value,
      // age: form.age ? parseInt(form.age) : null
    }
    
    const result = await request.put<any>(`${PageItem.commUrl}/edit`, params, {
      useErrMsg: true
    })
    
    if (result) {
      Taro.showToast({ title: '更新成功', icon: 'success' })

      setTimeout(() => {
        Taro.navigateBack()
      }, 1500)
    }
  } catch (error) {
    console.error('更新失败:', error)
    Taro.showToast({ title: '更新失败', icon: 'error' })
  }
}
</script>
